package com.example.timeplanning_teacher;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class FragmentConfirmPlans extends Fragment {

    private ListView taskView;
    private List<Map<String, Object>> datalist;
    private TaskViewAdapter adapter;
    private Toast Success;
    private Toast Failure;
    private SharedPreferences sp;
    private Toast timeOut_Toast;

    private int TaskId;
    Map<String, Object> taskinfo = new HashMap<String, Object>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_confirmplans, container, false);

        Success  = Toast.makeText(getActivity(),"成功",Toast.LENGTH_SHORT);
        Failure = Toast.makeText(getActivity(),"失败",Toast.LENGTH_SHORT);
        timeOut_Toast = Toast.makeText(getActivity(), "网络连接超时", Toast.LENGTH_SHORT);
        sp = getActivity().getSharedPreferences("parent", Context.MODE_PRIVATE);

        taskView = root.findViewById(R.id.task_view);
        View emptyView = root.findViewById(R.id.empty);
        taskView.setEmptyView(emptyView);
        datalist = getData();
        adapter = new TaskViewAdapter(getActivity(), datalist);
        taskView.setAdapter(adapter);
        taskView.setOnItemClickListener((parent, view, position, id) -> {
            taskinfo = (Map<String, Object>) taskView.getItemAtPosition(position);//SimpleAdapter返回Map
            TaskId = (int) taskinfo.get("task_id");
            Intent intent = new Intent();
            intent.setClass(getActivity(), TaskActivity.class);//this前面为当前activty名称，class前面为要跳转到得activity名称
            final SerializableMap myMap=new SerializableMap();
            myMap.setMap(taskinfo);//将map数据添加到封装的myMap中
            Bundle bundle=new Bundle();
            bundle.putSerializable("map", myMap);
            intent.putExtras(bundle);
            startActivity(intent);
            getActivity().overridePendingTransition(R.anim.trans_in, R.anim.no_anim);
        });

        taskView.setOnItemLongClickListener((parent, view, position, id) -> {
            taskinfo = (Map<String, Object>) taskView.getItemAtPosition(position);//SimpleAdapter返回Map
            TaskId = (int) taskinfo.get("task_id");
            String name = (String) taskinfo.get("content");
            final CommonDialog dialog = new CommonDialog(getActivity());
            dialog.setTitle("您确认要通过 " + name + " 吗？")
                    .setPositive("确定").setPositiveColor(Color.parseColor("#ff2d55"))
                    .setNegtive("取消")
                    //.setMessage("删除后无法恢复.")
                    .setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
                        @Override
                        public void onPositiveClick() {
                            PassSingleThread passSingleThread = new PassSingleThread(TaskId,Success,Failure,timeOut_Toast);
                            passSingleThread.start();
                            dialog.dismiss();
                            refresh();
                        }

                        @Override
                        public void onNegtiveClick() {
                            dialog.dismiss();
                        }
                    }).show();
            return true;
        });

        return root;

    }

    //从数据库获取数据
    public List<Map<String, Object>> getData() {
        datalist = new ArrayList<Map<String, Object>>();
        FragmentConfirmPlans.GetTasksThread getTasksThread = new GetTasksThread();
        getTasksThread.start();
        while(getTasksThread.isAlive());
        return datalist;
    }

    @Override
    public void onStart() {
        super.onStart();
        refresh();
    }

    public class GetTasksThread extends Thread{
        String student_username = sp.getString("student_username","");
        public void run(){
            try {
                String json = "{\n" +
                        "  \"username\": \"" + student_username + "\"\n" +
                        "}";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://58.58.36.198:9900/task/checkByUsername")
                        .post(RequestBody.create(MediaType.parse("application/json"),json))
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                JSONObject jsonObject= JSONObject.parseObject(responseData);
                int code=(int)jsonObject.get("code");
                if(code == 100){
                    JSONArray jsonArray = (JSONArray) jsonObject.get("data");
                    JSONObject Tasks;
                    for(int i=0;i<jsonArray.size();i++){
                        Tasks = (com.alibaba.fastjson.JSONObject) jsonArray.get(i);
                        datalist.add(i,Tasks);
                    }
                    //Success.show();
                }
                else{
                    Failure.show();
                }
            }catch (Exception e){
                e.printStackTrace();
                timeOut_Toast.show();
            }
        }
    }

    //刷新listview
    public void refresh() {
        //刷新list
        datalist.clear();
        datalist = getData();
        adapter = new TaskViewAdapter(getActivity(), datalist);
        taskView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    public static FragmentConfirmPlans newInstance() {
        return new FragmentConfirmPlans();
    }
}
